package handler;

import com.sun.net.httpserver.HttpExchange;
import constant.Constants;
import model.CustomerSessions;
import model.StakeManager;
import model.Session;
import util.ResponseUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * @Description 客户投注额
 * @Author admin
 * @Date 2024-12-25 11:44
 */
public class StakeHandler {
    private final CustomerSessions customerSessions;
    private final StakeManager stakeManager;

    public StakeHandler(CustomerSessions customerSessions, StakeManager stakeManager) {
        this.customerSessions = customerSessions;
        this.stakeManager = stakeManager;
    }

    public void doHandler(String betOfferIdStr, HttpExchange exchange) throws IOException {
        int betOfferId = Integer.parseInt(betOfferIdStr);
        String query = exchange.getRequestURI().getQuery();
        Map<String, String> queryParams = parseQuery(query);
        String sessionKey = queryParams.get(Constants.SESSION_KEY);
        if (sessionKey == null) {
            ResponseUtil.sendErrorResponse(exchange, Constants.ERROR_CODE, "Session key is missing");
            return;
        }
        int customerId = this.getCustomerIdFromSession(sessionKey);
        if (customerId == -1) {
            ResponseUtil.sendErrorResponse(exchange, Constants.INVALID_CODE, "Invalid session key");
            return;
        }
        int stake = Integer.parseInt(ResponseUtil.readRequestBody(exchange));
        stakeManager.updateBettingOffer(betOfferId, customerId, stake);
        ResponseUtil.sendResponse(exchange, "Stake Success");
    }

    private int getCustomerIdFromSession(String sessionKey) {
        for (Map.Entry<Integer, Session> entry : customerSessions.getSessions().entrySet()) {
            if (entry.getValue().getSessionKey().equals(sessionKey)) {
                return entry.getKey();
            }
        }
        return -1;
    }

    private Map<String, String> parseQuery(String query) {
        Map<String, String> result = new HashMap<>();
        if (query == null) {
            return result;
        }
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            if (keyValue.length == 2) {
                result.put(keyValue[0], keyValue[1]);
            }
        }
        return result;
    }
}